<!DOCTYPE html>
<html lang="zh-cn">

<head><title>
    使用 Go &#43; Gin 实现一个简单的 Json 服务器 | 
    
    ZZY2357 的博客</title>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="description" content="有时在学习前端的时候，不得不用一下一些 API，但是又找不到自己想要的数据，所以这个时候可以自己制作一个。这里我们使用 GO 语言和 Gin 框架来做一个。
搭建项目 cd $GOPATH/src/github.com/zzy2357 # 创建文件夹 mkdir simple-json-server cd ./simple-json-server # 初始化 Go Mod go mod init # 创建主文件 touch main.go 写代码 package main import ( // 导入模块 	&#34;github.com/gin-gonic/gin&#34; ) func main() { r := gin.Default() r.GET(&#34;/&#34;, func(c *gin.Context) { // 跨域设置  c.Header(&#34;Access-Control-Allow-Origin&#34;, &#34;*&#34;) // 200 状态码 	c.JSON(200, gin.H{ // Json 数据 	&#34;message&#34;: &#34;Hello world!&#34;, }) }) // 运行服务器，端口为 8000 	r.
    ">


<meta property="og:title" content="使用 Go &#43; Gin 实现一个简单的 Json 服务器" />
<meta property="og:description" content="有时在学习前端的时候，不得不用一下一些 API，但是又找不到自己想要的数据，所以这个时候可以自己制作一个。这里我们使用 GO 语言和 Gin 框架来做一个。
搭建项目 cd $GOPATH/src/github.com/zzy2357 # 创建文件夹 mkdir simple-json-server cd ./simple-json-server # 初始化 Go Mod go mod init # 创建主文件 touch main.go 写代码 package main import ( // 导入模块 	&#34;github.com/gin-gonic/gin&#34; ) func main() { r := gin.Default() r.GET(&#34;/&#34;, func(c *gin.Context) { // 跨域设置  c.Header(&#34;Access-Control-Allow-Origin&#34;, &#34;*&#34;) // 200 状态码 	c.JSON(200, gin.H{ // Json 数据 	&#34;message&#34;: &#34;Hello world!&#34;, }) }) // 运行服务器，端口为 8000 	r." />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://zzy2357.gitee.io/posts/simple-gin-json-server/" />
<meta property="article:published_time" content="2020-06-11T20:15:43+08:00" />
<meta property="article:modified_time" content="2020-06-11T20:15:43+08:00" />

<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="使用 Go &#43; Gin 实现一个简单的 Json 服务器"/>
<meta name="twitter:description" content="有时在学习前端的时候，不得不用一下一些 API，但是又找不到自己想要的数据，所以这个时候可以自己制作一个。这里我们使用 GO 语言和 Gin 框架来做一个。
搭建项目 cd $GOPATH/src/github.com/zzy2357 # 创建文件夹 mkdir simple-json-server cd ./simple-json-server # 初始化 Go Mod go mod init # 创建主文件 touch main.go 写代码 package main import ( // 导入模块 	&#34;github.com/gin-gonic/gin&#34; ) func main() { r := gin.Default() r.GET(&#34;/&#34;, func(c *gin.Context) { // 跨域设置  c.Header(&#34;Access-Control-Allow-Origin&#34;, &#34;*&#34;) // 200 状态码 	c.JSON(200, gin.H{ // Json 数据 	&#34;message&#34;: &#34;Hello world!&#34;, }) }) // 运行服务器，端口为 8000 	r."/>

<meta itemprop="name" content="使用 Go &#43; Gin 实现一个简单的 Json 服务器">
<meta itemprop="description" content="有时在学习前端的时候，不得不用一下一些 API，但是又找不到自己想要的数据，所以这个时候可以自己制作一个。这里我们使用 GO 语言和 Gin 框架来做一个。
搭建项目 cd $GOPATH/src/github.com/zzy2357 # 创建文件夹 mkdir simple-json-server cd ./simple-json-server # 初始化 Go Mod go mod init # 创建主文件 touch main.go 写代码 package main import ( // 导入模块 	&#34;github.com/gin-gonic/gin&#34; ) func main() { r := gin.Default() r.GET(&#34;/&#34;, func(c *gin.Context) { // 跨域设置  c.Header(&#34;Access-Control-Allow-Origin&#34;, &#34;*&#34;) // 200 状态码 	c.JSON(200, gin.H{ // Json 数据 	&#34;message&#34;: &#34;Hello world!&#34;, }) }) // 运行服务器，端口为 8000 	r.">
<meta itemprop="datePublished" content="2020-06-11T20:15:43&#43;08:00" />
<meta itemprop="dateModified" content="2020-06-11T20:15:43&#43;08:00" />
<meta itemprop="wordCount" content="146">



<meta itemprop="keywords" content="go," />
<link rel="canonical" href="https://zzy2357.gitee.io/posts/simple-gin-json-server/" />

<link rel="icon" type="image/png" href="https://zzy2357.gitee.io/image/favicon.ico">

<link rel="stylesheet" href="/css/font-awesome.min.css">
<link rel="stylesheet" href="/css/bulma.min.css">





<script src=/js/ramium.js></script>
<link rel="stylesheet" href=/css/ramium.css>





</head>

<body><nav class="navbar is-dark" role="navigation" aria-label="main navigation">
  <div class="navbar-brand">
    <a class="navbar-item" href=/>
      
      <strong>ZZY2357 的博客 </strong>
      
    </a>

    <a role="button" class="navbar-burger burger" aria-label="menu" aria-expanded="false"
      data-target="navbarBasicExample">
      <span aria-hidden="true"></span>
      <span aria-hidden="true"></span>
      <span aria-hidden="true"></span>
    </a>
  </div>

  <div id="navbarBasicExample" class="navbar-menu">
    <div class="navbar-start">
      
      
      <a class="navbar-item" href="/">主页</a>
      
      
      
      <div class="navbar-item has-dropdown is-hoverable">
        <a class="navbar-link">博客</a>
        <div class="navbar-dropdown">
          
          <a class="navbar-item" href="/tags/">所有标签</a>
          
          <a class="navbar-item" href="/posts/">所有文章</a>
          
        </div>
      </div>
      
      
      
      <a class="navbar-item" href="/about/">关于</a>
      
      
      
      <a class="navbar-item" href="/index.xml">RSS</a>
      
      
    </div>

    <div class="navbar-end">
      
      <a class="navbar-item navgithub" href="https://github.com/zzy2357" target="_blank">
        <i class="fa fa-github fa-2x"></i>
      </a>
      

      
    </div>
  </div>
</nav><div class="columns is-centered">
        <div id="page-body" class="column is-7">

<div class="content blog">
    <h1>使用 Go &#43; Gin 实现一个简单的 Json 服务器</h1>

    <div id="infobar" class="level is-mobile">
        <div class="level-left">
            
            <div class="level-item">
                <p class="subtitle info date">Jun 11, 2020
                </p>
            </div>
            

            <div class="level-item">
                <p class="subtitle info">
                    2 mins read
                </p>
            </div>
        </div>
        <div class="level-right is-hidden-touch">
            <div class="tags">
                
                <a class="tag is-dark is-rounded" href="/tags/go">Go</a>
                
            </div>
        </div>
    </div>

    <div class="tags is-hidden-desktop">
        
        <a class="tag is-dark is-rounded" href="/tags/go">Go</a>
        
    </div>

    <div class="blog-text">
        

        <p>有时在学习前端的时候，不得不用一下一些 API，但是又找不到自己想要的数据，所以这个时候可以自己制作一个。这里我们使用 GO 语言和 Gin 框架来做一个。</p>
<h2 id="搭建项目">搭建项目</h2>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-sh" data-lang="sh">cd $GOPATH/src/github.com/zzy2357
<span style="color:#75715e"># 创建文件夹</span>
mkdir simple-json-server
cd ./simple-json-server
<span style="color:#75715e"># 初始化 Go Mod</span>
go mod init
<span style="color:#75715e"># 创建主文件</span>
touch main.go
</code></pre></div><h2 id="写代码">写代码</h2>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">main</span>

<span style="color:#f92672">import</span> (
  <span style="color:#75715e">// 导入模块
</span><span style="color:#75715e"></span>	<span style="color:#e6db74">&#34;github.com/gin-gonic/gin&#34;</span>
)

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#a6e22e">r</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Default</span>()
	<span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">GET</span>(<span style="color:#e6db74">&#34;/&#34;</span>, <span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Context</span>) {
    <span style="color:#75715e">// 跨域设置
</span><span style="color:#75715e"></span>    <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Header</span>(<span style="color:#e6db74">&#34;Access-Control-Allow-Origin&#34;</span>, <span style="color:#e6db74">&#34;*&#34;</span>)
    <span style="color:#75715e">// 200 状态码
</span><span style="color:#75715e"></span>		<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">JSON</span>(<span style="color:#ae81ff">200</span>, <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">H</span>{
      <span style="color:#75715e">// Json 数据
</span><span style="color:#75715e"></span>			<span style="color:#e6db74">&#34;message&#34;</span>: <span style="color:#e6db74">&#34;Hello world!&#34;</span>,
		})
  })
  <span style="color:#75715e">// 运行服务器，端口为 8000
</span><span style="color:#75715e"></span>	<span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">Run</span>(<span style="color:#e6db74">&#34;:8000&#34;</span>)
}
</code></pre></div><h2 id="运行">运行</h2>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-sh" data-lang="sh">go run ./main.go
<span style="color:#75715e"># 以下为输出</span>
<span style="color:#f92672">[</span>GIN-debug<span style="color:#f92672">]</span> <span style="color:#f92672">[</span>WARNING<span style="color:#f92672">]</span> Creating an Engine instance with the Logger and Recovery middleware already attached.

<span style="color:#f92672">[</span>GIN-debug<span style="color:#f92672">]</span> <span style="color:#f92672">[</span>WARNING<span style="color:#f92672">]</span> Running in <span style="color:#e6db74">&#34;debug&#34;</span> mode. Switch to <span style="color:#e6db74">&#34;release&#34;</span> mode in production.
 - using env:   export GIN_MODE<span style="color:#f92672">=</span>release
 - using code:  gin.SetMode<span style="color:#f92672">(</span>gin.ReleaseMode<span style="color:#f92672">)</span>

<span style="color:#f92672">[</span>GIN-debug<span style="color:#f92672">]</span> GET    /                         --&gt; main.main.func1 <span style="color:#f92672">(</span><span style="color:#ae81ff">3</span> handlers<span style="color:#f92672">)</span>
<span style="color:#f92672">[</span>GIN-debug<span style="color:#f92672">]</span> Listening and serving HTTP on :8000
</code></pre></div><h3 id="试试效果">试试效果</h3>
<p>打开浏览器，浏览 <code>http://localhost:8000</code>：</p>
<pre><code>{&quot;message&quot;:&quot;Hello world!&quot;}
</code></pre><p>打开 JS 控制台输入：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#a6e22e">fetch</span>(<span style="color:#e6db74">&#39;http://loclhost:8000&#39;</span>)
  .<span style="color:#a6e22e">then</span>((<span style="color:#a6e22e">res</span>) =&gt; <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">json</span>())
  .<span style="color:#a6e22e">then</span>((<span style="color:#a6e22e">data</span>) =&gt; <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">data</span>));

<span style="color:#75715e">// {message: &#34;Hello world!&#34;}
</span><span style="color:#75715e">// message: &#34;Hello world!&#34;
</span></code></pre></div><p>成功！:-)</p>

    </div>
</div><div id="social-media-share" class="has-text-centered">
	<p><i>Sharing is caring!</i></p>
	<br>
	
	<div class="share-buttons">
	    <a  href="https://www.facebook.com/sharer/sharer.php?u=https%3a%2f%2fzzy2357.gitee.io%2fposts%2fsimple-gin-json-server%2f"
	        onclick="socialMediaPopUp(this.href, '', 500, 500); return false;"
	        title="Share on Facebook. Opens in a new window.">
	        <img src=/img/icons/45px/facebook.png>
	    </a>

	    <a  href="https://twitter.com/intent/tweet?text=%e4%bd%bf%e7%94%a8%20Go%20%2b%20Gin%20%e5%ae%9e%e7%8e%b0%e4%b8%80%e4%b8%aa%e7%ae%80%e5%8d%95%e7%9a%84%20Json%20%e6%9c%8d%e5%8a%a1%e5%99%a8&url=https%3a%2f%2fzzy2357.gitee.io%2fposts%2fsimple-gin-json-server%2f"
	        onclick="socialMediaPopUp(this.href, '', 500, 500); return false;"
	        title="Share on Twitter. Opens in a new window." >
	        <img src=/img/icons/45px/twitter.png>
	    </a>

		<a  href="http://www.reddit.com/submit?url=https%3a%2f%2fzzy2357.gitee.io%2fposts%2fsimple-gin-json-server%2f"
	        onclick="socialMediaPopUp(this.href, '', 900, 500); return false;"
	        title="Share on Reddit. Opens in a new window." >
	        <img src=/img/icons/45px/reddit.png>
	    </a>

	    <a  href="http://pinterest.com/pin/create/button/?url=https%3a%2f%2fzzy2357.gitee.io%2fposts%2fsimple-gin-json-server%2f"
	        onclick="socialMediaPopUp(this.href, '', 900, 500); return false;"
	        title="Share on Pinterest. Opens in a new window." >
	        <img src=/img/icons/45px/pinterest.png>
	    </a>

	    <a  href="http://www.tumblr.com/share/link?url=https%3a%2f%2fzzy2357.gitee.io%2fposts%2fsimple-gin-json-server%2f"
	        onclick="socialMediaPopUp(this.href, '', 900, 500); return false;"
	        title="Share on Tumblr. Opens in a new window." >
	        <img src=/img/icons/45px/tumblr.png>
	    </a>

		<a  href="https://www.linkedin.com/shareArticle?mini=true&url=https%3a%2f%2fzzy2357.gitee.io%2fposts%2fsimple-gin-json-server%2f
			&title=%e4%bd%bf%e7%94%a8%20Go%20%2b%20Gin%20%e5%ae%9e%e7%8e%b0%e4%b8%80%e4%b8%aa%e7%ae%80%e5%8d%95%e7%9a%84%20Json%20%e6%9c%8d%e5%8a%a1%e5%99%a8&summary=%e6%9c%89%e6%97%b6%e5%9c%a8%e5%ad%a6%e4%b9%a0%e5%89%8d%e7%ab%af%e7%9a%84%e6%97%b6%e5%80%99%ef%bc%8c%e4%b8%8d%e5%be%97%e4%b8%8d%e7%94%a8%e4%b8%80%e4%b8%8b%e4%b8%80%e4%ba%9b%20API%ef%bc%8c%e4%bd%86%e6%98%af%e5%8f%88%e6%89%be%e4%b8%8d%e5%88%b0%e8%87%aa%e5%b7%b1%e6%83%b3%e8%a6%81%e7%9a%84%e6%95%b0%e6%8d%ae%ef%bc%8c%e6%89%80%e4%bb%a5%e8%bf%99%e4%b8%aa%e6%97%b6%e5%80%99%e5%8f%af%e4%bb%a5%e8%87%aa%e5%b7%b1%e5%88%b6%e4%bd%9c%e4%b8%80%e4%b8%aa%e3%80%82%e8%bf%99%e9%87%8c%e6%88%91%e4%bb%ac%e4%bd%bf%e7%94%a8%20GO%20%e8%af%ad%e8%a8%80%e5%92%8c%20Gin%20%e6%a1%86%e6%9e%b6%e6%9d%a5%e5%81%9a%e4%b8%80%e4%b8%aa%e3%80%82%0a%e6%90%ad%e5%bb%ba%e9%a1%b9%e7%9b%ae%20cd%20%24GOPATH%2fsrc%2fgithub.com%2fzzy2357%20%23%20%e5%88%9b%e5%bb%ba%e6%96%87%e4%bb%b6%e5%a4%b9%20mkdir%20simple-json-server%20cd%20.%2fsimple-json-server%20%23%20%e5%88%9d%e5%a7%8b%e5%8c%96%20Go%20Mod%20go%20mod%20init%20%23%20%e5%88%9b%e5%bb%ba%e4%b8%bb%e6%96%87%e4%bb%b6%20touch%20main.go%20%e5%86%99%e4%bb%a3%e7%a0%81%20package%20main%20import%20%28%20%2f%2f%20%e5%af%bc%e5%85%a5%e6%a8%a1%e5%9d%97%20%09%26%2334%3bgithub.com%2fgin-gonic%2fgin%26%2334%3b%20%29%20func%20main%28%29%20%7b%20r%20%3a%3d%20gin.Default%28%29%20r.GET%28%26%2334%3b%2f%26%2334%3b%2c%20func%28c%20%2agin.Context%29%20%7b%20%2f%2f%20%e8%b7%a8%e5%9f%9f%e8%ae%be%e7%bd%ae%20%20c.Header%28%26%2334%3bAccess-Control-Allow-Origin%26%2334%3b%2c%20%26%2334%3b%2a%26%2334%3b%29%20%2f%2f%20200%20%e7%8a%b6%e6%80%81%e7%a0%81%20%09c.JSON%28200%2c%20gin.H%7b%20%2f%2f%20Json%20%e6%95%b0%e6%8d%ae%20%09%26%2334%3bmessage%26%2334%3b%3a%20%26%2334%3bHello%20world%21%26%2334%3b%2c%20%7d%29%20%7d%29%20%2f%2f%20%e8%bf%90%e8%a1%8c%e6%9c%8d%e5%8a%a1%e5%99%a8%ef%bc%8c%e7%ab%af%e5%8f%a3%e4%b8%ba%208000%20%09r.&source=rafed123.github.io"
	        onclick="socialMediaPopUp(this.href, '', 900, 500); return false;"
	        title="Share on LinkedIn. Opens in a new window." >
	        <img src=/img/icons/45px/linkedin.png>
	    </a>

	    <a  href="mailto:?subject=%e4%bd%bf%e7%94%a8%20Go%20%2b%20Gin%20%e5%ae%9e%e7%8e%b0%e4%b8%80%e4%b8%aa%e7%ae%80%e5%8d%95%e7%9a%84%20Json%20%e6%9c%8d%e5%8a%a1%e5%99%a8&amp;body=Check out this site https%3a%2f%2fzzy2357.gitee.io%2fposts%2fsimple-gin-json-server%2f"
	        title="Share via Email. Opens in a new window." >
	        <img src=/img/icons/45px/mail.png>
	    </a>
	</div>
</div>


<br>
<div id="disqus_thread"></div>
<script type="text/javascript">
    (function () {
        
        
        if (window.location.hostname == "localhost")
            return;

        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        var disqus_shortname = '';
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>


        </div>
    </div>

<footer class="footer has-background-dark">
    <div class="content has-text-centered has-text-white">
        <p>
            © 2020 Ramium. Powered by
            <a class="has-text-light" href="https://github.com/gohugoio/hugo" target="_blank">
            Hugo</a>. Theme
            <a class="has-text-light" href="https://github.com/rafed123/ramium/" target="_blank">
                Ramium.
            </a>
        </p>
    </div>
</footer>
</body>

</html>